package com.icez.indicator_view

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout

/**
 * 指示器
 * @sample 
 * @author Icez
 */
class IndicatorView @JvmOverloads constructor(
    context: Context, val attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {

    private var mIndicatorViewAdapter:IndicatorViewAdapter<*> ?= null

    private var mSelectedPosition:Int = 0

    private var mSpace:Int = 0

    init {
        orientation = HORIZONTAL
        gravity = Gravity.CENTER
        initStyleValue()
    }

    private fun initStyleValue(){
        val typedArray = context.obtainStyledAttributes(attrs,R.styleable.IndicatorView)
        mSpace = typedArray.getDimensionPixelOffset(R.styleable.IndicatorView_space,20)
        typedArray.recycle()
    }

    fun <T> setAdapter(mIndicatorViewAdapter: IndicatorViewAdapter<T>){
        this.mIndicatorViewAdapter = mIndicatorViewAdapter
        initChildView()
    }

    private fun initChildView(){
        if(mIndicatorViewAdapter==null || mIndicatorViewAdapter?.mData.isNullOrEmpty() || (mIndicatorViewAdapter?.mData?.size?:0) <= 1){
            return
        }
        removeAllViews()
        for(i in 0 until mIndicatorViewAdapter!!.mData!!.size){
            var childView: ViewGroup ?= null
            if(mSelectedPosition == i){
                childView = mIndicatorViewAdapter!!.getSelectedLayoutView(context)
            }else{
                childView = mIndicatorViewAdapter!!.getNormalLayoutView(context)
            }
            childView.setPadding(mSpace,0,mSpace,0)
            addView(childView)
        }
    }

    fun setSelectPosition(mSelectedPosition:Int){
        this.mSelectedPosition = mSelectedPosition
        initChildView()
    }
}